
var timeout;//用于存储定时器的变量	
var count=0;

var token=T.p('token');
console.log("token--------------------------------"+token);

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'buss/busscamerainfo/list?token='+token,
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '设备序列号', name: 'serialNum', index: 'serial_num', width: 50 }, 			
			{ label: '设备验证码', name: 'authCode', index: 'auth_code', width: 50 }, 
			{ label: '所属田块', name: 'tkName', index: 'farmland_info_id', width: 80 }, 
			{ label: '基地', name: 'deptName', index: 'dept_id', width: 50 }, 
			{ label: '安装位置', name: 'position', index: 'position', width: 80 }, 
			{ label: '添加用户', name: 'createName', index: 'create_name', width: 50 }, 			
			{ label: '添加时间', name: 'createTime', index: 'create_time', width: 100 }, 
			{ label: '最后修改用户姓名', name: 'updateName', index: 'update_name', width: 80 }, 		
			{ label: '最后修改时间', name: 'updateTime', index: 'update_time', width: 100 }, 						
			{ label: '操作',name: 'serialNum', index: 'serial_num', width: 50,
				formatter: function(value, options, row){
					return '<a href="JavaScript:;" onclick="vm.operation('+value+')">更多</a>'
				}
			}, 
			/*{ label: '排序编号', name: 'orderNum', index: 'order_num', width: 80 }, 			
			{ label: '创建人id', name: 'createId', index: 'create_id', width: 80 }, 			
			{ label: '创建用户姓名', name: 'createName', index: 'create_name', width: 80 }, 			
			{ label: '创建时间', name: 'createTime2', index: 'create_time2', width: 80 }, 			
			{ label: '修改人id', name: 'updateId', index: 'update_id', width: 80 }, 			
			{ label: '修改时间', name: 'updateTime', index: 'update_time', width: 80 }, 			
			{ label: '修改用户姓名', name: 'updateName', index: 'update_name', width: 80 }, 			
			{ label: '版本号', name: 'version', index: 'version', width: 80 }, 			
			{ label: '删除标识 -1：删除 0：正常', name: 'gcFlag', index: 'gc_flag', width: 80 }		*/	
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    
    // jq validate 校验 (需要校验的字段必须加上name属性/扩充校验写在validate-methods.js中)
    $("#ajaxForm").validate({
        //重写showErrors
        showErrors: function (errorMap, errorList) {
            var msg = "";
            $.each(errorList, function (i, v) {
                //在此处用了layer的方法,显示效果更美观
            	console.log(v.element);
                layer.tips(v.message, v.element, {
                	tips:[1,'#f3857c'], 
                	time: 2000, 
                	tipsMore: true
            	});
            });
        },
        //失去焦点时验证 
        onfocusout:  function (element) { $(element).valid(); }, 
    });
    
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		bussCameraInfo: {},
		q:{},	
		serialNumber:null,//序列号，用于控制云台
		tongdao:null,//通道，用于控制云台
		token:null,//token，用于控制云台
		tklist:[],//田块集合
	},
	methods: {
		query: function () {
			vm.reload(true);
		},
		add: function(){
			vm.title = "新增";
			vm.bussCameraInfo = {};
			vm.addLayer();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
            vm.title = "修改";
            
            vm.getInfo(id);
            
            vm.addLayer();
		},
		saveOrUpdate: function (event) {
			// 进行校验
			if(!$("#ajaxForm").valid()){
				layer.closeAll("loading");
				return;
			}
		
			var url = vm.bussCameraInfo.id == null ? "buss/busscamerainfo/save?token="+token : "buss/busscamerainfo/update?token="+token;
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.bussCameraInfo),
			    success: function(r){
			    	layer.closeAll("loading");
			    	if(r.code === 0){
			    		layer.closeAll();
						alert('操作成功', function(index){
							$("#jqGrid").trigger("reloadGrid");
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "buss/busscamerainfo/delete?token="+token,
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "buss/busscamerainfo/info/"+id+"?token="+token, function(r){
                vm.bussCameraInfo = r.bussCameraInfo;
            });
		},
		reload: function (event) {
			//vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			if(event){
				page = 1;
			}
			
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
           		postData:{'name': vm.q.name}
            }).trigger("reloadGrid");
		},
		addLayer: function(){
            layer.open({
                type: 1,
                offset: '20px',
                skin: 'layui-layer-molv',
                title: vm.title,
                area: ['550px', '420px'],
                shade: 0.2,
                shadeClose: false,
                content: jQuery("#addLayer"),	
                btn: ['确定', '取消'],
                btn1: function (index) {
                	layer.load();
                	vm.saveOrUpdate();
                },
                success: function(layero, index) {
                    layerResize(index);
                }
            });
        },
        //动态赋予弹出层的video标签的src属性
        operation:function(serialNum){
        	//赋值给用于云台控制的序列号
        	vm.serialNumber=serialNum;
        	//初始化一些参数，通道号和token
        	getTongdao();
        	//获取摄像头的接口连接参数
        	$.get(baseURL + "sys/config/info/1?token="+token, function(r){ 
        		console.log("获取摄像头的接口连接参数--------------");
                console.log(r);
                var data={
            			accessToken:r.config.remark,
            			'source':''+serialNum+':1'
            		}
                //开启直播并初始化弹出层
                beginzb(data);            
            });              	        	
        },
        //长按按钮触发启动云台
        changan:function(num){
        	//#moveLeft 表示需要监听长按事件的元素
        	timeout= setTimeout(function() {       		
        	    console.log("我长按了");
        	    ytxz(num);
        	    }, 1);//鼠标按下1毫秒后发生
        },
        //鼠标离开触发停止云台
        songkai:function(num){	
        	console.log("我松开了");
        	stopyt(num);
        	clearTimeout(timeout);//清理掉定时器
        },
        //鼠标悬浮清空时间容器
        getOut:function(num){   
        	if(!isBlank(timeout)){
        		console.log("我清理了");        		
            	clearTimeout(timeout);//清理掉定时器
            	timeout=undefined;
        	}      	
        },
        //摄像页面弹出层
        shexiang:function(data){
        	layer.open({
                type: 1,
                offset: '20px',
                skin: 'layui-layer-molv',
                title: '摄像头操作管理',
                area: ['660px', '500px'],
                shade: 0.2,
                shadeClose: false,
                content: jQuery("#auditLayer"),	
                btn: ['关闭'],
                btn1: function (index) { 
                	//关闭直播
                	endzb(data);
                	//关闭弹出框
                	layer.close(index);
                },  
                /*success: function(layero, index) {
                    layerResize(index);
                }*/
            });
        },
        getTkList:function(){
        	$.get(baseURL + "buss/bussfarmlandinfo/list?token="+token, function(r){ 
        		console.log(r);
        		vm.tklist=r.page.list;
        	})       	
        }
	},
	mounted:function(){
		this.getTkList();
	}	
});

//控制云台
function ytxz(num){
	var data={
		accessToken:vm.token,
		deviceSerial:vm.serialNumber,
		channelNo:vm.tongdao,
		direction:num,
		speed:1
	}
	$.ajax({
		type: 'POST',
	    url: 'https://open.ys7.com/api/lapp/device/ptz/start',
	    data: data,
	    success: function(r){
	    	console.log("开始云台控制打印信息------------------");
			console.log(r);			
		}
	});
}
//停止云台
function stopyt(num){
	var data={
		accessToken:vm.token,
		deviceSerial:vm.serialNumber,
		channelNo:vm.tongdao,
		direction:num,
		speed:1
	}
	$.ajax({
		type: 'POST',
	    url: 'https://open.ys7.com/api/lapp/device/ptz/stop',
	    data: data,
	    success: function(r){
	    	console.log("停止云台控制打印信息------------------");
			console.log(r);
		}
	});
}
//开通直播功能
function beginzb(data){
	$.ajax({
		type: 'POST',
	    url: 'https://open.ys7.com/api/lapp/live/video/open',
	    data: data,
	    success: function(r){
	    	console.log("开通直播功能打印信息------------------");
			console.log(r);
			//获取摄像头的直播信息
			getshexiangtou(data);
		}
	}); 
}
//结束直播功能
function endzb(data){
	$.ajax({
		type: 'POST',
	    url: 'https://open.ys7.com/api/lapp/live/video/close',
	    data: data,
	    success: function(r){
	    	console.log("关闭直播功能打印信息------------------");
			console.log(r);
		}
	});
}
//获取摄像头的直播信息
function getshexiangtou(data){
	$.ajax({
		type: 'POST',
	    url: 'https://open.ys7.com/api/lapp/live/address/get',
	    data: data,
	    success: function(r){
	    	console.log("获取直播地址打印信息------------------");
			console.log(r);	
			//先删除video的src属性
			$('#source123').removeAttr('src'); 
			//给video赋予src属性
			$('#source123').attr('src',r.data[0].rtmpHd); 
			//只有当count=0时才会初始化插件
			if(count==0){
				//初始化视频插件
				var player = new EZUIKit.EZUIPlayer('myPlayer');
				//player.stop();
			}					
			//摄像头弹出层
			vm.shexiang(data);
			count++;
		}
	});
}
//获取指定设备的通道信息
function getTongdao(){	
	//获取摄像头的接口连接参数          
    $.ajax({
    	type: 'get',
    	url: baseURL + "sys/config/info/1?token="+token,
    	async:false,
    	success: function(r){
    		console.log(r);
    		vm.token=r.config.remark;	
    	    var data={
    	    		accessToken:r.config.remark,
    	        	deviceSerial:vm.serialNumber
    	    }
    	    $.ajax({
    	    	type: 'POST',
    	    	url: 'https://open.ys7.com/api/lapp/device/camera/list',
    	    	data: data,
    	    	async:false,
    	    	success: function(r){
    	    		console.log("获取指定设备的通道信息------------------");
    	    		console.log(r);	
    	    		vm.tongdao=r.data[0].channelNo;  
    	    	}
    	    });       	        
    	}
    });                   
}